package com.yxhl.zoume.core.tripsmgmt.ui.adapter;

import android.graphics.drawable.GradientDrawable;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.protobuf.JudgeEntry;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.protobuf.OrderPayStatus;
import com.yxhl.protobuf.OrderRideStatus;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.ui.custom.CheckBoxLayout;
import com.yxhl.zoume.core.func.appraisal.model.AppraisalDriverInfo;
import com.yxhl.zoume.core.tripsmgmt.ui.event.HistoryTripsItemClickEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.event.JumpCommentEvent;
import com.yxhl.zoume.data.rxbus.RxBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 项目名称：Ferrari
 * Created by menggod on 16/11/29 .
 * 历史行程RecyclerView列表适配器
 */
public class HistoryTripsAdapter extends BaseQuickAdapter<BizOrder, HistoryTripsAdapter.HistoryViewHolder> {

    private static final String TAG = "PassengerListAdapter";
    private BizOrder clickOrder;
    private final List<BizOrder> mDataList;

    public HistoryTripsAdapter(List<BizOrder> data) {
        super(R.layout.item_history_trips,data);
        this.mDataList = data;
    }

    @Override
    protected void convert(HistoryViewHolder historyViewHolder, BizOrder bizOrder) {
        historyViewHolder.onBindHistoryViewHolder(bizOrder);
    }

    @Override
    protected HistoryViewHolder createBaseViewHolder(View view) {
        return new HistoryViewHolder(view);
    }

    public class HistoryViewHolder extends BaseViewHolder {

        @BindView(R.id.rl_history_trips_item_container)
        LinearLayout containerRl;

        //type icon
        @BindView(R.id.iv_include_trips_item_icon)
        ImageView bizTypeIcon;

        //body view
        @BindView(R.id.tv_include_trips_item_start_station)
        TextView startStation;
        @BindView(R.id.tv_include_trips_item_start_time)
        TextView startTime;
        @BindView(R.id.tv_include_trips_item_start_data)
        TextView startData;
        @BindView(R.id.tv_include_trips_item_destination)
        TextView destination;

        //bottom view
        @BindView(R.id.tv_trips_item_trip_status)
        TextView tripStatusTv;

        @BindView(R.id.tv_trips_item_fee)
        TextView price;
        @BindView(R.id.tv_trips_item_passenger_amount)
        TextView amount;


        @BindView(R.id.rl_trips_item_order_status)
        FrameLayout orderStatusFrame;
        @BindView(R.id.tv_trips_item_order_status)
        TextView orderStatusTv;
        @BindView(R.id.cbl_trips_item_judge)
        CheckBoxLayout itemJudgeCbl;


        public HistoryViewHolder(View itemView) {
            super(itemView);
            if(itemView instanceof  LinearLayout) {
                ButterKnife.bind(this, itemView);
            }
        }

        void onBindHistoryViewHolder(BizOrder bizOrder) {
            if (bizOrder != null) {
                OrderBizType bizType = bizOrder.getBizType();
                setBizTypeIcon(bizType);
                setStartStation(bizOrder.getStart());
                setDestination(bizOrder.getDestination());
                setStartTimeAndData(bizOrder.getGmtDepart());

                setPriceAndPassengerCount(bizOrder);
                setTripStatus(bizOrder);
                setOrderStatus(bizOrder);
            }
        }

        @OnClick(R.id.rl_history_trips_item_container)
        public void onItemCLick(View view) {
            int position = getLayoutPosition();
            if (position >= 0 && position < mDataList.size()) {
                clickOrder = (BizOrder) mDataList.get(position);
            }
            if (clickOrder != null) {
                RxBus.getInstance().send(new HistoryTripsItemClickEvent(containerRl, clickOrder));
            }
        }

        void setBizTypeIcon(OrderBizType bizType) {
            switch (bizType) {
                case ORDER_BIZ_SHARE:
                case ORDER_BIZ_CHARTER:
                    bizTypeIcon.setImageResource(R.drawable.ic_kuaiche);
                    break;
                case TICKET:
                case OBT_DABA_TICKET:
                    bizTypeIcon.setImageResource(R.drawable.ic_bashi_002);
                    break;
                case OBT_DIY_BUS:
                    bizTypeIcon.setImageResource(R.drawable.ic_dingzhibashibiaoqian);
                    break;
                case OBT_FT_BUS:
                    bizTypeIcon.setImageResource(R.drawable.ic_bashibiaoqian);
                    break;
                case OFFICIAL_BUS_WAY:
                    bizTypeIcon.setImageResource(R.drawable.ic_dancheng_gongwu);
                    break;
                case OFFICIAL_BUS_TIME:
                    bizTypeIcon.setImageResource(R.drawable.ic_fenshi_gongwu);
                    break;
                case SPECIAL_BUS_WAY:
                    bizTypeIcon.setImageResource(R.drawable.ic_special_bus_way);
                    break;
                case SPECIAL_BUS_TIME:
                    bizTypeIcon.setImageResource(R.drawable.ic_special_bus_time);
                    break;
            }
        }

        void setStartStation(String station) {
            if (!TextUtils.isEmpty(station)) {
                startStation.setText(station);
            } else {
                startStation.setText("");
            }
        }

        void setDestination(String station) {
            if (!TextUtils.isEmpty(station)) {
                destination.setText(station);
            } else {
                destination.setText("—— ——");
            }
        }

        /**
         * @param timeStamp
         */
        void setStartTimeAndData(String timeStamp) {
            if (!TextUtils.isEmpty(timeStamp)) {
                String[] strings = timeStamp.split(" ");
                startData.setText(strings[0]);
                startTime.setText(strings[1]);
            }
        }

        /**
         * 必须注意这个地方  不然条目复用显示就会出问题
         *
         * @param bizOrder
         */
        void setPriceAndPassengerCount(BizOrder bizOrder) {
            OrderBizType bizType = bizOrder.getBizType();
            switch (bizType) {
                case TICKET:
                    price.setText("¥" + bizOrder.getTotalFee());
                    amount.setText(String.format("(%d人)", bizOrder.getAmount()));
                    price.setVisibility(View.VISIBLE);
                    amount.setVisibility(View.VISIBLE);
                    break;
                case ORDER_BIZ_SHARE:
                case ORDER_BIZ_CHARTER:
                    price.setText("");
                    amount.setText(String.format("%d人", bizOrder.getAmount()));
                    price.setVisibility(View.VISIBLE);
                    amount.setVisibility(View.VISIBLE);
                    break;
                case OFFICIAL_BUS_WAY:
                case OFFICIAL_BUS_TIME:
                    price.setVisibility(View.INVISIBLE);
                    amount.setVisibility(View.INVISIBLE);
                    break;
                case SPECIAL_BUS_WAY:
                case SPECIAL_BUS_TIME:
                    price.setVisibility(View.INVISIBLE);
                    amount.setVisibility(View.INVISIBLE);
                    break;
                default:
                    price.setText("¥" + bizOrder.getTotalFee());
                    amount.setText(String.format("(%d人)", bizOrder.getAmount()));
                    price.setVisibility(View.VISIBLE);
                    amount.setVisibility(View.VISIBLE);
            }
        }

        /**
         * 设置底栏左侧 行程状态
         *
         * @param bizOrder
         */
        void setTripStatus(BizOrder bizOrder) {
            if (bizOrder != null) {
                OrderPayStatus payStatus = bizOrder.getPayStatus();
                OrderBizType bizType = bizOrder.getBizType();
                OrderRideStatus rideStatus = bizOrder.getRideStatus();

                String tripStatusStr;
                switch (bizType) {
                    case ORDER_BIZ_SHARE:
                    case ORDER_BIZ_CHARTER:
                        tripStatusStr = getTripStatusForSpecialCar(rideStatus);
                        break;
                    case TICKET:
                    case OBT_DABA_TICKET:
                        tripStatusStr = getTripStatusForTicketBus(payStatus);
                        break;
                    case OBT_DIY_BUS:
                    case OBT_FT_BUS:
                        tripStatusStr = getTripStatusForZouMeBus(payStatus);
                        break;
                    case OFFICIAL_BUS_WAY:
                    case OFFICIAL_BUS_TIME:
                        tripStatusStr = getTripStatusForSpecialCar(rideStatus);
                        break;
                    case SPECIAL_BUS_WAY:
                    case SPECIAL_BUS_TIME:
                        tripStatusStr = getTripStatusForSpecialCar(rideStatus);
                        break;
                    default:
                        tripStatusStr = "";
                }
                tripStatusTv.setText(tripStatusStr);
            }
        }


        /**
         * 当前行程状态有：1 2 8
         * 1——显示：未支付；
         * 2——显示：已支付；
         * 8——显示：部分退票（已购车票，部分退票）。
         * <p>
         * 历史行程状态：3，4，5，6，7，9，10
         * 3——显示：已过期（购票但未乘车，也未退票，直到超过退票时间）；
         * 4——显示：退票中（全部退票）；
         * 5——显示：已退票（由售票口执行退票操作后状态改变）；
         * 6——显示：已完成（正常购票，乘车，司机确认完成行程）；
         * 7——显示：已取消（主动取消，或者超时未支付）；
         * 9——不需要显示，状态等同于退票中；
         * 10——显示：已完成（正常购票，退部分票，剩余的完成行程）
         * 定制巴士的行程状态
         *
         * @param payStatus
         * @return
         */
        @NonNull
        private String getTripStatusForZouMeBus(OrderPayStatus payStatus) {
            String tripStatusStr;
            switch (payStatus) {
                case CREATED:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_created);
                    break;
                case PAID:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_paid);
                    break;
                case PAY_INVALID:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_invalid);
                    break;
                case OPS_REFUNDING:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_refunding);
                    break;
                case OPS_REFUND:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_refund);
                    break;
                case PART_FINISH:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_part_finish);
                    break;
                case ORDER_FINISH:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_finish);
                    break;
                case PAY_CANCEL:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_cancel);
                    break;
                case OPS_PART_REFUND:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_part_refunding);
                    break;
//                case OPS_NO_REFUND://未退票
//                    tripStatusStr = "";
//                    break;
                default:
                    tripStatusStr = "";
            }
            return tripStatusStr;
        }

        /**
         * 新地巴士的行程状态
         *
         * @param payStatus
         * @return
         */
        private String getTripStatusForTicketBus(OrderPayStatus payStatus) {
            String tripStatusStr;
            switch (payStatus) {
                case CREATED:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_created);
                    break;
                case PAID:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_paid);
                    break;
                case PAY_INVALID:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_invalid);
                    break;
                case OPS_REFUNDING:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_refunding);
                    break;
                case OPS_REFUND:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_refund);
                    break;
                case PART_FINISH:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_part_finish);
                    break;
                case ORDER_FINISH:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_finish);
                    break;
                case PAY_CANCEL:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_cancel);
                    break;
                case OPS_PART_REFUND:
                    tripStatusStr = mContext.getString(R.string.trip_detail_pay_status_part_refunding);
                    break;
                default:
                    tripStatusStr = "";
            }
            return tripStatusStr;
        }

        /**
         * 快车的行程状态
         *
         * @param rideStatus
         * @return
         */
        @NonNull
        private String getTripStatusForSpecialCar(OrderRideStatus rideStatus) {

            String tripStatusStr;
            switch (rideStatus) {
                case UN_SEND://未派车
                    tripStatusStr = mContext.getString(R.string.route_detail_no_charter);
                    break;
                case UN_TAKEN://未上车
                    tripStatusStr = mContext.getString(R.string.route_detail_wait_charter);
                    break;
                case TAKEN://已上车
                case PART_TAKEN: //部分上车
                    tripStatusStr = mContext.getString(R.string.route_detail_take_charter);
                    break;
                case ARRIVED://已到站
                case PART_ARRIVED: //部分已到站
                    tripStatusStr = mContext.getString(R.string.route_detail_finish_charter);
                    break;
                case RIDE_INVALID://未乘坐
                case DROP: //已放弃
                    tripStatusStr = mContext.getString(R.string.route_detail_cancel_charter);
                    break;
                default:
                    tripStatusStr = "";
            }
            return tripStatusStr;
        }


        /**
         * 设置底栏右侧 订单状态
         *
         * @param bizOrder
         */
        void setOrderStatus(final BizOrder bizOrder) {
            OrderBizType bizType = bizOrder.getBizType();
            switch (bizType) {
                case ORDER_BIZ_SHARE:
                case ORDER_BIZ_CHARTER:
                    setOrderStatusForSpecialCar(bizOrder);
                    break;
                case TICKET:
                case OBT_DABA_TICKET:
                    setOrderStatusForTicketBus(bizOrder);
                    break;
                case OBT_DIY_BUS:
                case OBT_FT_BUS:
                    setOrderStatusForZouMeBus(bizOrder);
                    break;
                case OFFICIAL_BUS_TIME:
                case OFFICIAL_BUS_WAY:
                    setOrderStatusForZouMeOfficialCar(bizOrder);
                    break;
                case SPECIAL_BUS_WAY:
                case SPECIAL_BUS_TIME:
                    setOrderStatusForSpecialCar(bizOrder);
                    break;
                default:
                    orderStatusFrame.setVisibility(View.INVISIBLE);
                    itemJudgeCbl.setVisibility(View.INVISIBLE);
                    break;
            }
        }

        private void setOrderStatusForZouMeOfficialCar(BizOrder bizOrder) {
            OrderRideStatus rideStatus = bizOrder.getRideStatus();
            switch (rideStatus) {
                case ARRIVED:
                    showJudge(bizOrder);
                    break;
                default:
                    itemJudgeCbl.setVisibility(View.INVISIBLE);
                    orderStatusFrame.setVisibility(View.INVISIBLE);
                    break;
            }
        }


        private void setOrderStatusForSpecialCar(BizOrder bizOrder) {
            OrderRideStatus rideStatus = bizOrder.getRideStatus();
            switch (rideStatus) {
                case ARRIVED:
                    showJudge(bizOrder);
                    break;
                default:
                    itemJudgeCbl.setVisibility(View.INVISIBLE);
                    orderStatusFrame.setVisibility(View.INVISIBLE);
                    break;
            }
        }

        private void setOrderStatusForTicketBus(BizOrder bizOrder) {
            orderStatusFrame.setVisibility(View.INVISIBLE);
            itemJudgeCbl.setVisibility(View.INVISIBLE);
        }

        private void setOrderStatusForZouMeBus(BizOrder bizOrder) {
            OrderPayStatus payStatus = bizOrder.getPayStatus();
            switch (payStatus) {
                case ORDER_FINISH:
                    showJudge(bizOrder);
                    break;
                default:
                    orderStatusFrame.setVisibility(View.INVISIBLE);
                    itemJudgeCbl.setVisibility(View.INVISIBLE);
            }
        }

        /**
         * 显示去评价/评价星星
         *
         * @param bizOrder
         */
        private void showJudge(BizOrder bizOrder) {
            final String orderId = bizOrder.getOrderSerial();
            JudgeEntry judgeEntry = bizOrder.getJudge();
            if (judgeEntry != null) {
                int judgePoint = judgeEntry.getJudgePoint();
                if (judgePoint <= 0) {
                    displayToJudge(orderId);
                } else {
                    showJudgePoint(judgePoint);
                }
            } else {
                displayToJudge(orderId);
            }
        }

        /**
         * 显示评价星星
         *
         * @param judgePoint
         */
        private void showJudgePoint(int judgePoint) {
            orderStatusFrame.setVisibility(View.INVISIBLE);
            orderStatusFrame.setClickable(false);
            itemJudgeCbl.setVisibility(View.VISIBLE);
            itemJudgeCbl.setCheckEnable(false);
            itemJudgeCbl.setCheckedCount(judgePoint);
        }

        /**
         * 显示去评价
         *
         * @param orderId
         */
        private void displayToJudge(final String orderId) {
            itemJudgeCbl.setVisibility(View.INVISIBLE);
            orderStatusFrame.setVisibility(View.VISIBLE);
            orderStatusFrame.setClickable(true);
          //  orderStatusFrame.setBackgroundColor(mContext.getResources().getColor(R.color.bg_trips_payment));
            GradientDrawable background = (GradientDrawable) orderStatusFrame.getBackground();
            background.setColor(mContext.getResources().getColor(R.color.bg_trips_payment));
            orderStatusTv.setVisibility(View.VISIBLE);
            orderStatusTv.setTextColor(mContext.getResources().getColor(R.color.white));
            orderStatusTv.setText(mContext.getString(R.string.trip_item_order_status_judge));

            orderStatusFrame.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getLayoutPosition();
                    AppraisalDriverInfo driverInfo = getAppraisalDriverInfo(position);
                    RxBus.getInstance().send(new JumpCommentEvent(driverInfo));
                }
            });
        }


        private AppraisalDriverInfo getAppraisalDriverInfo (int position){
            AppraisalDriverInfo driverInfo=new AppraisalDriverInfo();
            clickOrder=(BizOrder) mDataList.get(position);
            if(clickOrder!=null){
                String start=(TextUtils.isEmpty(clickOrder.getAvgDriverPoint())?"4":clickOrder.getAvgDriverPoint());
                driverInfo.setOrderId(clickOrder.getOrderSerial())
                        .setDriverName(clickOrder.getDriverName())
                        .setHistoryScore(Double.valueOf(start))
                        .setPlateNumber(clickOrder.getVehicleNo());
            }
            return driverInfo;
        }


    }
}
